package com.haina.shop.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.haina.shop.constant.MessageConstant;
import com.haina.shop.constant.OrderCloseTypeConstant;
import com.haina.shop.constant.OrderStatusConstant;
import com.haina.shop.context.BaseContext;
import com.haina.shop.domain.*;
import com.haina.shop.dto.*;
import com.haina.shop.mapper.*;
import com.haina.shop.result.IPageIndexImg;
import com.haina.shop.result.ServiceResult;
import com.haina.shop.service.OrderService;
import com.haina.shop.vo.*;
import com.haina.shop.vo.temp.ShopCartItems;
import lombok.Getter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
* @author 48077
* @description 针对表【tz_order(订单表)】的数据库操作Service实现
* @createDate 2024-07-31 18:34:29
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
    implements OrderService{
    @Autowired
    private OrderMapper mapper;
    @Autowired
    private OrderItemMapper itemMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private ShopDetailMapper shopMapper;
    @Autowired
    private UserAddrOrderMapper addrOrderMapper;
    @Autowired
    private UserAddrMapper userAddrMapper;
    @Autowired
    private BasketMapper basketMapper;
    @Autowired
    private ProdMapper prodMapper;
    @Autowired
    private RedisTemplate  redisTemplate;

    /**;
     * 获取我的订单订单数量
     */
    @Override
    public ServiceResult<OrderCountVO> getOrderCount() {
        Long userId = BaseContext.getCurrentId();
        //根据订单状态查询数量
        Integer unPayCount=mapper.selectListByStatus(OrderStatusConstant.UN_PAY,userId);
        Integer payCount=mapper.selectListByStatus(OrderStatusConstant.PAYD,userId);
        Integer consignmentCount=mapper.selectListByStatus(OrderStatusConstant.CONSINGNMENT,userId);
        Integer confirmCount=mapper.selectListByStatus(OrderStatusConstant.CONFIRM,userId);
        Integer successCount=mapper.selectListByStatus(OrderStatusConstant.SUCCESS,userId);
        Integer closeCount=mapper.selectListByStatus(OrderStatusConstant.CLOSE,userId);
        Integer allCount=unPayCount+payCount+consignmentCount+confirmCount+successCount+closeCount;
        OrderCountVO orderCountVO = new OrderCountVO(allCount,unPayCount,payCount,consignmentCount,confirmCount,
                successCount,closeCount);
        return ServiceResult.success(orderCountVO);
    }
    /**
     * 根据订单状态获取订单列表信息，状态为0时获取所有订单
     * @param dto
     */
    @Override
    public ServiceResult<IPageIndexImg<OrderVO>> getOrderList(OrderListDTO dto) {
        Long userId = BaseContext.getCurrentId();
        //获取数据
        Integer status = dto.getStatus();
        Long size = dto.getSize();
        Long current = dto.getCurrent();
        //设置分页初始值
        PageHelper.startPage(Math.toIntExact(current), Math.toIntExact(size));
        Page<Order> orderPage;
        //判断状态是否为0
        if(status==0){
            //获取所有订单
            orderPage= mapper.selectAll(userId);
        }else{
            //根据状态获取订单
            orderPage=mapper.selectByStatus(status,userId);
        }
        //创建IPageIndexImg对象
        IPageIndexImg<OrderVO> iPageIndexImg=new IPageIndexImg<>();
        iPageIndexImg.setSize(size);
        iPageIndexImg.setTotal(orderPage.getTotal());
        iPageIndexImg.setCurrent(current);
        iPageIndexImg.setPages(orderPage.getTotal()/size+1);
        //获取所有记录
        List<Order> orderList =orderPage.getResult();
        List<OrderVO> orderVOList=new ArrayList<>();
        for (Order order : orderList) {
            OrderVO vo = getVO(order);
            orderVOList.add(vo);
        }
        iPageIndexImg.setRecords(orderVOList);
        return ServiceResult.success(iPageIndexImg);
    }
    /**
     * 根据订单号获取订单详情信息
     * @param orderNumber
     */
    @Override
    public ServiceResult<OrderDetailVO> getOrderDetail(String orderNumber) {
        ///先根据订单号获取订单信息
        Order order=mapper.getByOrderNum(orderNumber);
        OrderDetailVO detailVO = getDetailVO(order);
        return ServiceResult.success(detailVO);
    }
    /**
     * 传入下单所需要的参数进行下单
     * @param dto
     * @return
     */
    @Override
    public ServiceResult<OrderConfirmVO> confirm(OrderParamDTO dto) {
        //预下单缓存名称
      String ORDER_CACHE_NAME="preOder-"+BaseContext.getCurrentId();
        //预下单缓存商品名称
      String ORDER_ITEM_CACHE_NAME="preOderItem-"+BaseContext.getCurrentId();
        UserAddrDto userAddrDto1 = new UserAddrDto();
        //首先需要判断用户是否输入收获地址
        if(dto.getAddrId()==0){
            //用户没有输入地址，将地址设置为默认地址
            //获取当前用户的默认地址
            Long userId = BaseContext.getCurrentId();
            UserAddr userAddr=userAddrMapper.selectAddr(userId,1);
            if(userAddr!=null){
                 BeanUtils.copyProperties(userAddr,userAddrDto1);
            }else{
                //用户没有默认地址返回null
                userAddrDto1=userAddrDto1;
            }
        }else{
            //用户输入了收获地址
            Long addrId = dto.getAddrId();
            UserAddr userAddr=userAddrMapper.selByAddrId(Math.toIntExact(addrId));
            BeanUtils.copyProperties(userAddr,userAddrDto1);
        }
        if(dto.getOrderItem()==null){
            //根据购物车ids获取所有的购物车信息
            List<Long> basketIds = dto.getBasketIds();
            LambdaQueryWrapper<Basket> wrapper = new LambdaQueryWrapper<>();
            //当前用户的购物车
            wrapper.in(Basket::getBasketId,basketIds).
                    eq(Basket::getUserId,BaseContext.getCurrentId());
            List<Basket> basketList = basketMapper.selectList(wrapper);
            Double actualAmount=0.0;
            Double totalAmount = 0.0;
            Integer totalCount=0;
            //对购物车进行遍历
            for (Basket basket:basketList) {
                Long prodId = basket.getProdId();
                Prod prod = prodMapper.getById(prodId);
                double oriPrice = prod.getOriPrice().doubleValue();
                double price = prod.getPrice().doubleValue();
                Integer basketCount = basket.getBasketCount();
                totalAmount += oriPrice * basketCount;
                actualAmount = price * basketCount;
                totalCount += basketCount;
            }
            //计算订单的优惠金额
            Double reduceAmount=totalAmount-actualAmount;
            OrderConfirmVO orderConfirmVO = new OrderConfirmVO();
            orderConfirmVO.setActualTotal(BigDecimal.valueOf(actualAmount));
            orderConfirmVO.setTotal(BigDecimal.valueOf(totalAmount));
            orderConfirmVO.setTotalCount(totalCount);
            orderConfirmVO.setOrderReduce(BigDecimal.valueOf(reduceAmount));
            //接下来构造UserAddrDto
            orderConfirmVO.setUserAddr(userAddrDto1);
            List<ShopCartOrderDto> shopCartOrderDtos=new ArrayList<>();
            //获取每个店铺的购物车信息，对查询到的购物车列表按照店铺id进行分组
            Map<Long, List<Basket>> collect = basketList.stream().collect(Collectors.groupingBy(Basket::getShopId));
            //遍历每个店铺的购物车
            List<ShopCartItems> shopCartItems=new ArrayList<>();
            for (Map.Entry<Long, List<Basket>> entry : collect.entrySet()) {
                Long shopId = entry.getKey();
                //每个店铺的所有购物车产品
                List<Basket> baskets = entry.getValue();
                //根据shopId获取shopName
                ShopDetail shopDetail = shopMapper.selectById(shopId);
                //创建ShopCartOrderDto对象
                ShopCartOrderDto dto2 = new ShopCartOrderDto();
                //创建ShopCartItems对象
                ShopCartItems items1 = new ShopCartItems();
                items1.setShopId(shopId);
                items1.setUserId(String.valueOf(BaseContext.getCurrentId()));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                String format = sdf.format(new Date());
                String orderNum = format;
                items1.setOrderNumber(orderNum);
                items1.setCreateTime(new Date());
                items1.setUpdateTime(new Date());
                dto2.setShopId(shopId);
                dto2.setShopName(shopDetail.getShopName());
                //对按照shopId划分处理的购车列表进行遍历
                Double actualAmount2=0.0;
                Double totalAmount2 = 0.0;
                Integer totalCount2=0;
                List<OrderItem> orderItems=new ArrayList<>();
                StringBuilder sb=new StringBuilder();
                for (Basket basket : baskets) {
                    Prod prod = prodMapper.getById(basket.getProdId());
                    //获取skuId
                    Sku sku = skuMapper.selectById(basket.getSkuId());
                    sb.append(prod.getProdName()).append(",");
                    double oriPrice = prod.getOriPrice().doubleValue();
                    double price = prod.getPrice().doubleValue();
                    Integer basketCount = basket.getBasketCount();
                    totalAmount2 += oriPrice * basketCount;
                    actualAmount2 = price * basketCount;
                    totalCount2 += basketCount;
                    OrderItem orderItem = new OrderItem(
                            shopId,orderNum,prod.getProdId(),basket.getSkuId(),
                            basket.getBasketCount(),prod.getProdName(),sku.getSkuName(),
                            prod.getPic(),BigDecimal.valueOf(price),String.valueOf(BaseContext.getCurrentId()),BigDecimal.valueOf(price*basketCount),
                            new Date(),0,"",basket.getBasketDate()
                    );
                    orderItems.add(orderItem);
                }
                String prodName=sb.toString();
                if(baskets.size()==1){
                    prodName= sb.substring(0, sb.length() - 1);
                }
                items1.setProdName(prodName);
                items1.setTotal(BigDecimal.valueOf(totalAmount2));
                items1.setActualTotal(BigDecimal.valueOf(actualAmount2));
                items1.setReduceAmount(BigDecimal.valueOf(totalAmount2-actualAmount2));
                items1.setFreightAmount(shopDetail.getFixedFreight());
                items1.setProductNums(totalCount2);
                dto2.setActualTotal(BigDecimal.valueOf(actualAmount2));
                dto2.setTotal(BigDecimal.valueOf(totalAmount2));
                dto2.setTotalCount(totalCount2);
                dto2.setTransfee(shopDetail.getFixedFreight());
                dto2.setDiscountReduce(BigDecimal.valueOf(totalAmount2-actualAmount2));
                dto2.setCouponReduce(null);
                dto2.setShopReduce(BigDecimal.valueOf(totalAmount2-actualAmount2));
                dto2.setRemarks(null);
                //购物车商品
                List<ShopCartItemDiscountDto> shopCartItemDiscountDtos=new ArrayList<>();
                //再对baskets根据discountId进行划分
                Map<Long, List<Basket>> collect1 = baskets.stream().collect(Collectors.groupingBy(Basket::getDiscountId));
                for (Map.Entry<Long, List<Basket>> longListEntry : collect1.entrySet()) {
                    ShopCartItemDiscountDto shopCartItemDiscountDto = new ShopCartItemDiscountDto();
                    shopCartItemDiscountDto.setChooseDiscountItemDto(null);
                    List<ShopCartItemDto> shopCartItemDtos=new ArrayList<>();
                    List<Basket> discountBasketList = longListEntry.getValue();
                    for (Basket basket : discountBasketList) {
                        //获取skuId
                        Sku sku = skuMapper.selectById(basket.getSkuId());
                        //获取产品id
                        Long prodId = basket.getProdId();
                        //根据id获取产品
                        Prod prod = prodMapper.selectById(prodId);
                        ShopCartItemDto shopCartItemDto = new ShopCartItemDto(
                                prod.getPrice().doubleValue(), sdf.format(basket.getBasketDate()),
                                basket.getBasketId(),basket.getDiscountId(),null,null,prod.getOriPrice().doubleValue(),
                                prod.getPic(),prod.getPrice().doubleValue(),basket.getBasketCount(),
                                prodId,prod.getProdName(),prod.getPrice().doubleValue()*basket.getBasketCount(),
                                null,shopId,shopDetail.getShopName(),basket.getSkuId(),sku.getSkuName()
                        );
                        shopCartItemDtos.add(shopCartItemDto);
                    }
                    shopCartItemDiscountDto.setShopCartItems(shopCartItemDtos);
                    shopCartItemDiscountDtos.add(shopCartItemDiscountDto);
                }
                dto2.setShopCartItemDiscounts(shopCartItemDiscountDtos);
                dto2.setCoupons(null);
                dto2.setOrderNumber(null);
                shopCartOrderDtos.add(dto2);
                //根据订单编号进行订单缓存(设置过期时间）
                redisTemplate.opsForValue().set(ORDER_CACHE_NAME,items1);
                //根据订单编号进行订单项缓存(设置过期时间）
                redisTemplate.opsForValue().set(ORDER_ITEM_CACHE_NAME,orderItems);
            }
            orderConfirmVO.setShopCartOrders(shopCartOrderDtos);
            orderConfirmVO.setCoupons(null);
            return ServiceResult.success(orderConfirmVO);
        }else{
            OrderItemParam orderItem = dto.getOrderItem();
            Integer prodCount = orderItem.getProdCount();
            Long prodId = orderItem.getProdId();
            Prod prod = prodMapper.selectById(prodId);
            //根据shopId获取shopName
            ShopDetail shopDetail = shopMapper.selectById(orderItem.getShopId());
            Sku sku = skuMapper.selectById(orderItem.getSkuId());
            ShopCartItems items1 = new ShopCartItems();
            items1.setShopId(shopDetail.getShopId());
            items1.setUserId(String.valueOf(BaseContext.getCurrentId()));
            items1.setCreateTime(new Date());
            items1.setUpdateTime(new Date());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String format = sdf.format(new Date());
            String orderNum = format;
            items1.setOrderNumber(orderNum);
            items1.setProdName(prod.getProdName());
            Integer count = orderItem.getProdCount();
            Double total=count * (prod.getOriPrice().doubleValue());
            Double actualTotal=count * (prod.getPrice().doubleValue());
            items1.setTotal(BigDecimal.valueOf(total));
            items1.setActualTotal(BigDecimal.valueOf(actualTotal));
            items1.setReduceAmount(BigDecimal.valueOf(total-actualTotal));
            items1.setFreightAmount(shopDetail.getFixedFreight());
            items1.setProductNums(count);
            OrderItem orderItem1 = new OrderItem(
                    orderItem.getShopId(), orderNum,prod.getProdId(),sku.getSkuId(),
                    count,prod.getProdName(),sku.getSkuName(),
                    prod.getPic(),prod.getPrice(),String.valueOf(BaseContext.getCurrentId()),BigDecimal.valueOf(total),
                    new Date(),0,"",new Date()
            );
            //构造key
            redisTemplate.opsForValue().set(ORDER_CACHE_NAME,items1);
            //根据订单编号进行订单项缓存(设置过期时间）
            redisTemplate.opsForValue().set(ORDER_ITEM_CACHE_NAME,orderItem1);

            List<ShopCartOrderDto> shopCartOrderDtos=new ArrayList<>();
            Double actualAmount = prod.getOriPrice().doubleValue()*prodCount;
            Double totalAmount = prod.getPrice().doubleValue()*prodCount;
            BigDecimal bigDecimal = new BigDecimal(0);
            List<ShopCartItemDiscountDto> shopCartItemDiscountDtos=new ArrayList<>();
            ShopCartItemDiscountDto shopCartItemDiscountDto = new ShopCartItemDiscountDto();
            shopCartItemDiscountDto.setChooseDiscountItemDto(null);
            List<ShopCartItemDto> shopCartItemDtos=new ArrayList<>();
            double price = prod.getPrice().doubleValue();
            double oriPrice = prod.getOriPrice().doubleValue();
            double reduceAmount=(oriPrice-price)*prodCount;
            List<DiscountDto> discountDtos=new ArrayList<>();
            ShopCartItemDto shopCartItemDto = new ShopCartItemDto(
               prod.getPrice().doubleValue(), sdf.format(new Date()), Long.valueOf(-1L),Long.valueOf(0L),discountDtos,"",prod.getOriPrice().doubleValue(),
                    prod.getPic(),prod.getPrice().doubleValue(),prodCount,prodId,prod.getProdName(),
                    price*prodCount,reduceAmount,orderItem.getShopId(),shopDetail.getShopName(),
                    orderItem.getSkuId(),sku.getSkuName()
            );
            shopCartItemDtos.add(shopCartItemDto);
            shopCartItemDiscountDto.setShopCartItems(shopCartItemDtos);

            shopCartItemDiscountDtos.add(shopCartItemDiscountDto);
            ShopCartOrderDto shopCartOrderDto = new ShopCartOrderDto(
                 orderItem.getShopId(),shopDetail.getShopName(),BigDecimal.valueOf(actualAmount),BigDecimal.valueOf(totalAmount),prodCount,
                    shopDetail.getFixedFreight(),BigDecimal.valueOf(totalAmount-actualAmount),
                    bigDecimal,BigDecimal.valueOf(totalAmount-actualAmount),null,shopCartItemDiscountDtos,null,null
            );
            shopCartOrderDtos.add(shopCartOrderDto);
            OrderConfirmVO orderConfirmVO = new OrderConfirmVO(
                  BigDecimal.valueOf(prod.getPrice().doubleValue()*prodCount), BigDecimal.valueOf(prod.getOriPrice().doubleValue()*prodCount),
                    prodCount,null,userAddrDto1,shopCartOrderDtos,null
            );

            return ServiceResult.success(orderConfirmVO);
        }

    }
    /**
     * 根据订单号确认收获
     * @param orderNumber
     * @return
     */
    @Override
    public ServiceResult receiptByOrderNum(String orderNumber) {
        //当前用户
        Long userId = BaseContext.getCurrentId();
        //根据订单号获取订单
       Order order= mapper.selectByOrderNum(userId,orderNumber);
       //修改状态为待评价
        order.setStatus(OrderStatusConstant.CONFIRM);
        order.setUpdateTime(new Date());
        //订单更新
        boolean update= updateById(order);
        if(update){
            return ServiceResult.success();
        }else return ServiceResult.success(MessageConstant.ORDER_UPDATE_STATUS_FAIL);
    }
    /**
     * 根据订单号取消订单
     * @param orderNumber
     * @return
     */
    @Override
    public ServiceResult cancalByOrderNum(String orderNumber) {
        //当前用户
        Long userId = BaseContext.getCurrentId();
        //根据订单号获取订单
        Order order= mapper.selectByOrderNum(userId,orderNumber);
        //修改状态为失败
        order.setStatus(OrderStatusConstant.CLOSE);
        //更新时间和取消时间设置,取消原因设置为用户取消订单
        order.setUpdateTime(new Date());
        order.setCancelTime(new Date());
        order.setCloseType(OrderCloseTypeConstant.USER_CANCEL);;
        //订单更新
        boolean update= updateById(order);
        if(update){
            return ServiceResult.success();
        }else return ServiceResult.success(MessageConstant.ORDER_UPDATE_STATUS_FAIL);
    }
    /**
     * 根据订单号删除订单
     * @param orderNumber
     * @return
     */
    @Override
    public ServiceResult deleteByOrderNum(String orderNumber) {
        //当前用户
        Long userId = BaseContext.getCurrentId();
        //根据订单号和当前用户id删除订单
        int rows=mapper.deleteByIdAndUserId(userId,orderNumber);
        if(rows>0){
            return ServiceResult.success();
        }else return ServiceResult.success(MessageConstant.ORDER_UPDATE_STATUS_FAIL);
    }
    /**
     * 提交订单
     * @paramparam
     * @return
     */
    @Override
    @Transactional
    public ServiceResult<OrderNumberVO> submit(SubmitOrderParam param) {
        //预下单缓存名称
        String ORDER_CACHE_NAME="preOder-"+BaseContext.getCurrentId();
        //预下单缓存商品名称
        String ORDER_ITEM_CACHE_NAME="preOderItem-"+BaseContext.getCurrentId();
        //获取缓存中的数据
        ShopCartItems shopCartItems = (ShopCartItems) redisTemplate.opsForValue().get(ORDER_CACHE_NAME);
        //插入订单数据库中
        Order order = new Order();
        BeanUtils.copyProperties(shopCartItems,order);
        order.setIsPayed(0);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setStatus(OrderStatusConstant.UN_PAY);
        int insert = mapper.insert(order);
        //插入订单项数据库中
        for (OrderItem item : (List<OrderItem>) redisTemplate.opsForValue().get(ORDER_ITEM_CACHE_NAME)) {
            itemMapper.insert(item);
        }
        //删除缓存中的数据
        redisTemplate.delete(ORDER_CACHE_NAME);
        redisTemplate.delete(ORDER_ITEM_CACHE_NAME);
        return ServiceResult.success(new OrderNumberVO(order.getOrderNumber()));
    }
    /**
     * 支付
     * @return
     */

    @Override
    public ServiceResult pay(PayDTO dto) {
        //根据orderNum进行订单状态更新
        Long userId = BaseContext.getCurrentId();
        Order order = mapper.selectByOrderNum(userId, dto.getOrderNumbers());
        order.setStatus(OrderStatusConstant.PAYD);
        order.setPayType(1);
        order.setPayTime(new Date());
        order.setIsPayed(1);
        boolean update = updateById(order);
        if(update){
            return ServiceResult.success();
        }else return ServiceResult.error(MessageConstant.ERROR_CODE,"支付失败");
    }

    //entity(order)->orderDetailVO
    public OrderDetailVO getDetailVO(Order order){
        Long shopId = order.getShopId();
        //计算总减金额
        Double reduceAmount=order.getTotal().doubleValue()-order.getActualTotal().doubleValue();
        //根据shopId获取shopName
        ShopDetail shopDetail = shopMapper.selectById(shopId);
        //根据订单地址id获取地址信息
        Long addrOrderId = order.getAddrOrderId();
        UserAddrOrder addr = addrOrderMapper.selectById(addrOrderId);
        //获取用户订单配送地址的地址id
        Long addrId = addr.getAddrId();
        //根据addrId查询用户地址表中是否是默认地址
        UserAddr userAddr = userAddrMapper.selByAddrId(Math.toIntExact(addrId));
        Integer commonAddr = userAddr.getCommonAddr();
        UserAddrDto userAddrDto = new UserAddrDto(
               addr.getAddrId(),addr.getReceiver(),addr.getProvince(),
               addr.getCity(),addr.getArea(),addr.getAddr(),addr.getMobile(),commonAddr,addr.getProvinceId(),
               addr.getCityId(),addr.getAreaId()
        );
        List<OrderItemDto2> orderItemDto2s=new ArrayList<>();
        //获取订单编号
        String orderNumber = order.getOrderNumber();
        //根据订单号获取所有所有的订单项
        List<OrderItem> orderItemList=itemMapper.getByOrderNum(orderNumber);
        for (OrderItem item : orderItemList) {
            //根据prodId获取购物车id
            Basket basket = basketMapper.selectByProdId(BaseContext.getCurrentId(), item.getProdId());
            //根据prodId获取产品的原始价格
            Prod prod = prodMapper.getById(item.getProdId());
            //计算商品实际金额
            double actualAmount = prod.getOriPrice().doubleValue() * (item.getProdCount());
            orderItemDto2s.add(new OrderItemDto2(
              item.getProdName(),item.getProdCount(),item.getPic(),
                    item.getPrice(),item.getProductTotalAmount(),
                    item.getProdId(),item.getSkuId(),item.getSkuName(),
                    basket.getBasketId(),BigDecimal.valueOf(actualAmount),basket.getDiscountId(),
                    null,null
            ));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return new OrderDetailVO(
            shopId,shopDetail.getShopName(),order.getActualTotal(),order.getTotal(),
               order.getProductNums(),userAddrDto,orderItemDto2s,order.getFreightAmount(),BigDecimal.valueOf(reduceAmount),
              BigDecimal.valueOf(0),BigDecimal.valueOf(0),sdf.format(order.getCreateTime()),order.getRemarks(),
                order.getStatus()
        );
    }

    //entity->VO
    public OrderVO getVO(Order order){
        Long userId = BaseContext.getCurrentId();
        //设置订单项
        List<OrderItemDto> orderItemDtos=new ArrayList<>();
        //根据order_num查询订单商品项
        String orderNumber = order.getOrderNumber();
        List<OrderItem> orderItems=itemMapper.selectListByOrderNum(orderNumber,userId);
        for (OrderItem orderItem : orderItems) {
            OrderItemDto dto = getDTO(orderItem);
            orderItemDtos.add(dto);
        }
        return new OrderVO(
            orderItemDtos,order.getOrderNumber(),order.getActualTotal(),order.getStatus()
        );
    }
    //entity(OrderItem)->DTO
    public OrderItemDto getDTO(OrderItem item){
        //根据skuId获取skuName
        Long skuId = item.getSkuId();
        String skuName=skuMapper.getDataById(skuId);
        return new OrderItemDto(
           item.getPic(),item.getProdName(),item.getProdCount(),
            item.getPrice(),skuName
        );
    }
}
// ProductClass是一个自定义类，用于封装产品ID和SKU ID
@Getter
class ProductClass {
    private final Long prodId;
    private final Long skuId;

    public ProductClass(Long prodId, Long skuId) {
        this.prodId = prodId;
        this.skuId = skuId;
    }
}
@Getter
class ShopItems{
    private  List<OrderItem> orderItems;
    public ShopItems(List<OrderItem> orderItems) {
        this.orderItems = orderItems;
    }
}




